--
-- Author: shunguo.chen
-- Date: 2018-04-03 16:12:33
--
-- CosKOFView	kof 选角界面
--

local CosKOFHeadRender = import(".renders.CosKOFHeadRender")
local CosKOFHeroRender = import(".renders.CosKOFHeroRender")
local CosKOFHeadTipRender = import(".renders.CosKOFHeadTipRender")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

ClassRef.VIEW_ROOT_RES = Res.CosplayKOFScene

local REMAIN_TIME_STR = L("left_time_sec")
local FINISH_TIME_STR = L("lua_code_text_397")
local OK_BTN_STR = L("lua_code_text_526")

function ClassRef:init()
	self._ui.bg:setContentSize(display.size)

	-- mid hero
	self._btnText = self._ui.Button_queding:getChildByName("name")
	self._ui.Button_queding:addClickEventListener(function()
			local data = self._curRender:getData()
			executeFunc(self._onOperate, "selectRole", data.id)
		end)
	self._ui.Button_quxiao:addClickEventListener(function()
			self:_unselectRender()
		end)

	local renders = {0,0,0}
	local posAry = {0,0,0}
	for i=1,3 do
		local node = self._ui["Panel_" .. i]
		local render = CosKOFHeroRender.create(node)
		render:setTag(i)
		render:onBtnClick(handler(self, self._onClickRender))
		renders[i] = render
		posAry[i] = render:getPositionX()
	end
	self._renders = renders
	self._renderPosAry = posAry

	-- 选中／取消选中 需要移动的距离
	self._moveDis = posAry[2] - posAry[1]

	-- head tip
	local tip = CosKOFHeadTipRender.create()
	tip:setVisible(false)
	self:addChild(tip)
	self._headTip = tip

	-- left head
	local panel = self._ui["Panel/Panel_left"]
	local heads = {0,0,0}
	for i=1,3 do
		local node = panel:getChildByName("head_" .. i)
		local render = CosKOFHeadRender.create(node)
		render:setIsEnemy(false)
		render:setSelected(false)
		render:setTouchTip(tip, 110)
		heads[i] = render
	end
	self._myHeads = heads

	-- right head
	local panel = self._ui["Panel/Panel_right"]
	local heads = {0,0,0}
	for i=1,3 do
		local node = panel:getChildByName("head_" .. i)
		local render = CosKOFHeadRender.create(node)
		render:setIsEnemy(true)
		render:setSelected(false)
		render:setTouchTip(tip, display.width-284)
		heads[i] = render
	end
	self._enemyHeads = heads

	-- 是否在选择动画中，在动画中消息更新过来延迟刷新自己信息
	self._isInAction = false
	-- 是否延迟更新信息
	self._delayRefresh = false
end

-- infos = {CosKOFInfo, ...}
function ClassRef:refresh(infos)
	self._data = infos
	self._myInfo = nil
	self._enemyInfo = nil
	for i,v in ipairs(infos) do
		if v:isMyTeam() then
			self._myInfo = v
		else
			self._enemyInfo = v
		end
	end

	self:_refreshMyInfo()
	self:_refreshEnemyInfo()
end

-- isMyTeam = true/false
function ClassRef:updateInfo(isMyTeam)
	if isMyTeam then
		if not self._isInAction then
			self:_refreshMyInfo()
			self:_refreshEnemyInfo()
		else
			self._delayRefresh = true
		end
	else
		self:_refreshEnemyInfo()
	end
end

function ClassRef:_refreshMyInfo()
	local myInfo = self._myInfo

	local isFinish = myInfo:isFinish()
	local roles = myInfo:getRoles()
	local roleLen = #roles
	local selectComp = roleLen == 3

	-- my heads
	for i,head in ipairs(self._myHeads) do
		head:setData(roles[i])
		head:setSelected(i == (roleLen + 1))
	end

	-- choose heros
	local showRoles = selectComp and roles or myInfo:getPoolRoles()
	for i,render in ipairs(self._renders) do
		render:setData(showRoles[i])
		render:setChoosed(selectComp)
	end

	-- reset renders while select comp
	if selectComp and self._curRender then
		self:_unselectRender()
	end

	self._ui.tips:stopAllActions()
	self:_refreshTime()
end

function ClassRef:_refreshTime()
	local remainTime = self._myInfo:getRestTime()
	local isFinish = self._myInfo:isFinish()
	if (remainTime == 0 and isFinish) or remainTime < 0 then
		-- 时间到并且完成，关闭界面
		executeFunc(self._onCloseView)
		return
	end

	if self._ui.tips:isVisible() then
		local str = isFinish and FINISH_TIME_STR or REMAIN_TIME_STR
		self._ui.tips:setString(string.format(str, remainTime))
	elseif self._ui.Button_queding:isVisible() then
		self._btnText:setString(string.format(OK_BTN_STR, remainTime))
	end

	self._ui.tips:performWithDelay(function() self:_refreshTime() end, 1)
end

function ClassRef:_refreshEnemyInfo()
	-- enemy heads
	local roleLen = self._myInfo:getRoleLen()
	local enemyRoles = self._enemyInfo:getRoles()
	for i,head in ipairs(self._enemyHeads) do
		local data
		if i <= roleLen then
			data = enemyRoles[i]
		end
		head:setData(data)
	end
end

function ClassRef:_onClickRender(render, op)
	local data = render:getData()
	if op == "openRole" then
		executeFunc(self._onOperate, "openRole", data)
	elseif op == "selectRole" then
		self:_selectRender(render)
	end
end

function ClassRef:_selectRender(render)
	if self._curRender then return end
	if self._isInSelect then return end
	self._isInSelect = true

	self._ui.tips:setVisible(false)

	self._curRender = render
	render:setSelected(true)
	local tag = render:getTag()
	local acts = {}
	for i,v in ipairs(self._renders) do
		if i ~= tag then
			local act = cca.seq({cca.fadeOut(0.1), cca.hide()})
			acts[#acts + 1] = cca.targeted(act, v)
		end
	end
	if tag ~= 2 then
		local dis = tag < 2 and self._moveDis or -self._moveDis
		acts[#acts + 1] = cca.targeted(cca.moveBy(0.2, dis, 0), render)
	end

	local scale1 = cca.scaleTo(0.15, 1.1)
	local scale2 = cca.scaleTo(0.15, 1)
	local func = cca.cb(function()
			self._isInSelect = false

			if self._myInfo:isFinish() then
				-- 动画结束时已经选人结束了，直接_unselectRender
				self:_unselectRender()
			else
				self._ui.Button_queding:setVisible(true)
				self._ui.Button_quxiao:setVisible(true)
				local remainTime = self._myInfo:getRestTime()
				self._btnText:setString(string.format(OK_BTN_STR, remainTime))
			end
		end)
	local action = cca.seq({cca.spawn(acts), scale1, scale2, func})
	render:runAction(action)
end

function ClassRef:_unselectRender()
	if not self._curRender then return end
	if self._isInSelect then return end
	self._isInSelect = true

	self._ui.Button_queding:setVisible(false)
	self._ui.Button_quxiao:setVisible(false)

	local render = self._curRender
	local tag = render:getTag()
	render:setSelected(false)

	local acts = {}
	if tag ~= 2 then
		local dis = tag < 2 and -self._moveDis or self._moveDis
		acts[#acts + 1] = cca.targeted(cca.moveBy(0.2, dis, 0), render)

		for i,v in ipairs(self._renders) do
			if i ~= tag then
				local act = cca.seq({cca.delay(0.1), cca.show(), cca.fadeIn(0.1)})
				acts[#acts + 1] = cca.targeted(act, v)
			end
		end
	else
		for i,v in ipairs(self._renders) do
			if i ~= tag then
				local act = cca.seq({cca.show(), cca.fadeIn(0.1)})
				acts[#acts + 1] = cca.targeted(act, v)
			end
		end
	end

	local func = cca.cb(function()
		self._curRender = nil
		self._isInSelect = false
		self._ui.tips:setVisible(true)

		local isFinish = self._myInfo:isFinish()
		local remainTime = self._myInfo:getRestTime()
		local str = isFinish and FINISH_TIME_STR or REMAIN_TIME_STR
		self._ui.tips:setString(string.format(str, remainTime))
	end)

	local action = cca.seq({cca.spawn(acts), func})
	render:runAction(action)
end

-- 选择动画 2. 左边新头像的动画
function ClassRef:_playHeadAction()
	local roles = self._myInfo:getRoles()
	local head = self._myHeads[#roles]

	head:playShowAction(roles[#roles], function()
		self._curRender:setVisible(true)
		self._isInAction = false
		if self._delayRefresh then
			self:_refreshMyInfo()
			self:_refreshEnemyInfo()
			self._delayRefresh = false
		end
		self:_unselectRender()
	end)
end

-- 选择动画 1. 中间角色的动画
function ClassRef:playSelectAction()
	if self._isInAction then return end

	if not self._aniNode then
		-- select action
		local node = self._ui["Panel/node_ami"]
		local timeline = cc.CSLoader:createTimeline(Res.CosplaySelectActionNode)
		timeline:setLastFrameCallFunc(function()
			self._aniNode:setVisible(false)
			self:_playHeadAction()
		end)
		node:runAction(timeline)
		
		self._aniTimeline = timeline
		self._aniParticle = node:findChild("Panel/flash_01")
		self._aniNode = node
	end

	self._aniNode:performWithDelay(function()
			if cc.isAlive(self._curRender) then
				self._curRender:setVisible(false)
			end
		end, app:getAnimationInterval() * 15)

	self._isInAction = true

	self._ui.Button_queding:setVisible(false)
	self._ui.Button_quxiao:setVisible(false)

	self._aniNode:setVisible(true)
	self._aniTimeline:gotoFrameAndPlay(0, false)
	self._aniParticle:resetSystem()
end

return ClassRef
